package com.wenzhoujie;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.wenzhoujie.adapter.DeliveryAddressAdapter;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.DeliveryModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.act.User_addr_listActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewInject;
import com.wenzhoujie.work.AppRuntimeWorker;

/**
 * 配送地址
 * 
 * @author js02
 * 
 */
public class DeliveryAddressActivty extends BaseActivity implements OnClickListener
{

	/** 设置页面模式 1:管理模式，0:选择模式 */
	public static final String EXTRA_DELIVERY_MODE = "extra_delivery_mode";

	public static final String EXTRA_RESULT_DELIVERY_MODEL = "extra_result_delivery_model";

	public static final int REQUEST_CODE_EDIT_ADDRESS = 1;
	public static final int REQUEST_CODE_ADD_ADDRESS = 2;

	public static final int RESULT_CODE_SELECT_DELIVERY_MODEL_SUCCESS = 10;

	@ViewInject(id = R.id.act_delivery_address_tv_add_address)
	private TextView mTvAddAddress = null;

	@ViewInject(id = R.id.act_delivery_address_lv_address)
	private PullToRefreshListView mLvAddress = null;

	private List<DeliveryModel> mListModel = new ArrayList<DeliveryModel>();
	private DeliveryAddressAdapter mAdapter = null;

	/** 1:管理模式，0:选择模式 */
	private int mModeOriginal = 1;
	/** 1:管理模式，0:选择模式 */
	private int mModeCurrent = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setmTitleType(TitleType.TITLE_SIMPLE);
		setContentView(R.layout.act_delivery_address);
		IocUtil.initInjectedView(this);
		init();
	}

	private void init()
	{
		getIntentData();
		initTitle(mModeCurrent);
		registeClick();
		bindDefaultData();
		initPullToRefreshListView();
		requestUsersAddress(false);
	}

	private void getIntentData()
	{
		String mode = getIntent().getStringExtra(EXTRA_DELIVERY_MODE);
		mModeOriginal = SDTypeParseUtil.getIntFromString(mode, 1);
		mModeCurrent = mModeOriginal;
	}

	private void initViewsState()
	{
		if (AppRuntimeWorker.getOnly_one_delivery() == 1)
		{
			mTvAddAddress.setVisibility(View.GONE);
		} else
		{
			mTvAddAddress.setVisibility(View.VISIBLE);
		}
	}

	private void initPullToRefreshListView()
	{
		mLvAddress.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.PULL_FROM_START);
		mLvAddress.setOnRefreshListener(new OnRefreshListener2<ListView>()
		{

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView)
			{
				requestUsersAddress(true);
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView)
			{
				// TODO Auto-generated method stub
			}
		});
		mLvAddress.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id)
			{
				if (mAdapter != null)
				{
					if (mModeCurrent == 1)
					{
						Intent intent = new Intent(DeliveryAddressActivty.this, AddDeliveryAddressActivity.class);
						intent.putExtra(AddDeliveryAddressActivity.EXTRA_DELIVERY_MODEL, mAdapter.getItem((int) id));
						startActivityForResult(intent, REQUEST_CODE_EDIT_ADDRESS);
					} else if (mModeCurrent == 0)
					{
						Intent intent = new Intent();
						intent.putExtra(EXTRA_RESULT_DELIVERY_MODEL, mAdapter.getItem((int) id));
						setResult(RESULT_CODE_SELECT_DELIVERY_MODEL_SUCCESS, intent);
						finish();
					}
				}
			}
		});
	}

	private void initTitle(int mode)
	{
		mTitleSimple.setmListener(new SDTitleSimpleListener()
		{

			@Override
			public void onRightButtonCLick_SDTitleSimple(View v)
			{
				if (mModeCurrent == 1)
				{
					mModeCurrent = 0;
				} else
				{
					mModeCurrent = 1;
				}
				initTitle(mModeCurrent);
				if (mAdapter != null)
				{
					mAdapter.updateMode(mModeCurrent);
				}
			}

			@Override
			public void onLeftButtonCLick_SDTitleSimple(View v)
			{
				finish();
			}
		});
		mTitleSimple.setTitleTop("收货地址");
		if (mode == 1)
		{
			mTitleSimple.setRightText("取消管理");
		} else
		{
			mTitleSimple.setRightText("管理");
		}

		if (mModeOriginal == 1)
		{
			mTitleSimple.setRightText("");
		}
	}

	private void bindDefaultData()
	{
		mAdapter = new DeliveryAddressAdapter(mListModel, this);
		mLvAddress.setAdapter(mAdapter);
		mAdapter.updateMode(mModeCurrent);
	}

	/**
	 * 请求用户地址
	 */
	private void requestUsersAddress(final boolean isRefresh)
	{
		if (AppHelper.isLogin())
		{
			RequestModel model = new RequestModel();
			model.put("act", "user_addr_list");
			model.putUser();
			RequestCallBack<String> handler = new RequestCallBack<String>()
			{

				@Override
				public void onStart()
				{
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo)
				{
					User_addr_listActModel actModel = JsonUtil.json2Object(responseInfo.result, User_addr_listActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel))
					{
						if (actModel.getResponse_code() == 1)
						{
							mListModel.clear();
							List<DeliveryModel> listDelivery = actModel.getItem();
							if (listDelivery != null && listDelivery.size() > 0)
							{
								initViewsState();
								if (AppRuntimeWorker.getOnly_one_delivery() == 1)
								{
									mListModel.add(listDelivery.get(0));
								} else
								{
									mListModel.addAll(listDelivery);
								}
							} else
							{
								mTvAddAddress.setVisibility(View.VISIBLE);
							}
							mAdapter.updateListViewData(mListModel);
						} else
						{

						}
					}
				}

				@Override
				public void onFailure(HttpException error, String msg)
				{

				}

				@Override
				public void onFinish()
				{
					AppHelper.hideLoadingDialog();
					mLvAddress.onRefreshComplete();
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		} else
		{
			startActivity(new Intent(getApplicationContext(), LoginNewActivity.class));
		}

	}

	private void registeClick()
	{
		mTvAddAddress.setOnClickListener(this);

	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.act_delivery_address_tv_add_address:
			clickAddAddress();
			break;

		default:
			break;
		}
	}

	/**
	 * 添加地址
	 */
	private void clickAddAddress()
	{
		// TODO 跳到添加收货地址界面
		startAddAddressActivity();
	}

	private void startAddAddressActivity()
	{
		Intent intent = new Intent(getApplicationContext(), AddDeliveryAddressActivity.class);
		startActivityForResult(intent, REQUEST_CODE_ADD_ADDRESS);
	}

	private void setOriginalMode()
	{
		mModeCurrent = mModeOriginal;
		initTitle(mModeCurrent);
		if (mAdapter != null)
		{
			mAdapter.updateMode(mModeCurrent);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (resultCode)
		{
		case AddDeliveryAddressActivity.RESULT_CODE_ADD_ADDRESS_SUCCESS:
			setResult(AddDeliveryAddressActivity.RESULT_CODE_ADD_ADDRESS_SUCCESS);
			mLvAddress.setRefreshing();
			setOriginalMode();
			break;
		case AddDeliveryAddressActivity.RESULT_CODE_DELETE_ADDRESS_SUCCESS:
			setResult(AddDeliveryAddressActivity.RESULT_CODE_DELETE_ADDRESS_SUCCESS);
			mLvAddress.setRefreshing();
			setOriginalMode();
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}